var schPerSet = (function ($) {
	var nurseid=''
	var sourceData,perList
	var copyDomHeight = 40*SCALE
	var topHeight = 0,bottomHeight=70
	var moveTimer
	var overHeight = 0,lastY;
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	
	//排班行Id@排班行最终人员排序「...... 「被拖动行Id@被拖动行最终人员排序@被拖动行停留位置组Id(ArgGroupDR)
	function changeArgShort(parr,block){
		var pdict = {'parr':parr} 
		var paramDict = {'method':'web.INMArgComm:ChangeArgRowSort','params':JSON.stringify(pdict),'type':'Method'}
		//console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msg'] != '1') {
				mui.toast('操作失败')
				return
			}
			if (block) {
				block()
			}
		}, function(errorStr) {
			mui.toast('操作失败')
			if (block) {
				block(true)
			}
			updatePersonList()
		});
	}
	//人员删除
	function deleteOnePerson(id){
		//ArgWardDR|病区Id^ArgStDate|开始日期^ArgEndDate|结束日期^ArgCrtUser|创建者user Id^ArgRemarks|排班表备注^ArgStatus|状态^rw|排班表Id^WardDesc|病区描述
		var argInfo=sourceData['argInfo']
		var ArgCrtUser = argInfo['ArgCrtUser'];
		var ArgStatus = argInfo['ArgStatus']
		var rw = argInfo['rw']
		var parr1 = 'ArgWardDR|'+sourceData.wardID+'^ArgStDate|'+sourceData.startDate+'^ArgEndDate|'+sourceData.endDate+
			'^ArgCrtUser|'+ArgCrtUser+'^ArgRemarks|'+argInfo.ArgRemarks+'^ArgStatus|'+ArgStatus+'^rw|'+rw+'^WardDesc|'+sourceData.wardDesc;
		var pdict = {'parr1':parr1,'persons':id} 
		var paramDict = {'method':'web.INMArgComm:DeleteArgPersons','params':JSON.stringify(pdict),'type':'Method'}
		//console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msg'] != '1') {
				mui.toast('删除失败')
				return
			}
			mui.toast('删除成功')
			getWardPersonList()
		}, function(errorStr) {
			mui.toast('删除失败')
		});
	}
	//移动分组
	function changeArgGroup(parr,type,block){
		//parr:排班表id^移动组Id parr1和parr2非空即可,后台用不到 type:U上移 D下移
		var pdict = {'parr':parr,'parr1':'1','parr2':'1','type':type} ;
		var paramDict = {'method':'web.INMArgComm:MoveArgGroup','params':JSON.stringify(pdict),'type':'Method'}
		//console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msg'] != '1') {
				mui.toast('操作失败')
				return
			}
			if (block) {
				block()
			}
		}, function(errorStr) {
			mui.toast('操作失败')
		});
	}
	
	// 删除分组
	function deleteOneGroup(id){
		var pdict = {'id':id}
		var paramDict = {'method':'web.INMArgComm:DeleteArgGroup','params':JSON.stringify(pdict),'type':'Method'}
		//console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msg'] != '1') {
				mui.toast('删除失败')
				return
			}
			mui.toast('删除成功')
			getWardPersonList()
		}, function(errorStr) {
			mui.toast('删除失败')
		});
	}
	
	function getWardPersonList(block){
		var pdict = {'nurseid':nurseid,'parr':sourceData.wardID+'^'+sourceData.startDate+'^'+sourceData.endDate}
		var paramDict = {'method':'web.INMArgComm:FindArrangeSubList','params':JSON.stringify(pdict),'type':'RecQuery'}
		//console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] != '1') {
				mui.toast(result['msg'])
				mui('#tbody')[0].innerHTML = ''
				return
			}
			perList = result['data']
			sourceData['locSchArr'] = perList
			updatePersonList()
			if (block) {
				block()
			}
		}, function(errorStr) {
			mui('#tbody')[0].innerHTML = ''
			mui.toast('操作失败');
		});
	}
	
	function updatePersonList(){
		var html = '';
		for (var i = 0; i < perList.length; i++) {
			var oneDict = perList[i]
			var className = 'perName'
			var perClass = 'person'
			var PerName = oneDict['PerName']
			var groupDR = oneDict['ArgGroupDR']
			var rowId = oneDict['ArgRowId']==undefined?"":oneDict['ArgRowId']
			var sort = oneDict['ArgPerSort']==undefined?"":oneDict['ArgPerSort']
			var id = groupDR
			if (oneDict['PerID'] == undefined) {
				className = 'groupName'
				perClass = ''
			}else{
				PerName = PerName.replace(oneDict['PerID'],"")
				id=oneDict['ArgPerDR']
			}
			var beds = oneDict['ArgPerBeds']!=undefined?oneDict['ArgPerBeds']:"";
			html += '<tr data-id="'+id+'" data-group="'+groupDR+'" data-row="'+rowId+'" data-sort="'+sort+'" data-beds="'+beds+'" class="'+perClass+'">'+
				'<td class="'+className+'">'+PerName+'</td>'+
				'<td class="btnTd"><div class="mui-icon mui-icon-trash"></div></td>'+
				'<td class="btnTd"><div class="mui-icon mui-icon-arrowthinup"></div></td>'+
				'<td class="btnTd"><div class="mui-icon mui-icon-arrowthindown"></div></td>'+
				'<td class="btnTd"><div class="mui-icon mui-icon-bars"></div></td></tr>'
		}
		mui('#tbody')[0].innerHTML = html
		if (html == '') {
			showNullTip('暂无人员');
		}
		overHeight = mui('#wrapper .mui-scroll')[0].clientHeight - mui('#wrapper')[0].clientHeight
	}
	function baseSetup(){
		mui('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		mui('body').on('tap','#addBtn',function(){
			if (sourceData['isOverdue']) {
				mui.toast('已超出修改期限')
				return
			}
			var webview = plus.webview.create('nurSchPerAdd.html', 'nurSchPerAdd', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'sourceData':sourceData});
			webview.show('fade-in');
		}) 
		mui('#tbody').on('tap','.mui-icon-trash',function(){
			if(notSchedTip()) return
			var thisDom = this;
			var tr = this.parentNode.parentNode
			var id = tr.getAttribute('data-id')
			var trClass = tr.getAttribute('class');
			var tip = '分组'
			if (trClass.indexOf('person') != -1) {
				tip = '人员'
			}
			
			tip += tr.querySelector('td').innerText
			mui.confirm('确认删除'+tip+'吗','删除提示',['取消','确认'],function (e) {
				if (e.index == 1) {
					if (trClass.indexOf('person') != -1) {
						deleteOnePerson(id)
					}else{
						deleteOneGroup(id)
					}
				}
			})
		})
		//向上
		mui('#tbody').on('tap','.mui-icon-arrowthinup',function(){
			upDownBtnTapped(this,'U')
		})
		//向下
		mui('#tbody').on('tap','.mui-icon-arrowthindown',function(){
			upDownBtnTapped(this,'D')
		})
		mui('#copyDom').on('tap','#cancelBtn',function(){
			var oldActive = $('.person.active')[0]
			if (oldActive) {
				oldActive.classList.remove('active')
			}
			if ($('tr.select')[0]) {
				$('tr.select')[0].classList.remove('select')
			}
			$('#copyDom')[0].style.display = 'none'
		})
		
		mui('#tbody').on('tap','.mui-icon-bars',dragBarsIconTapped);
		mui('#copyDom').on('touchstart','.dom',copyDomTouchStart);
		mui('#copyDom').on('touchmove','.dom',copyDomTouchMove);
		mui('#copyDom').on('touchend','.dom',copyDomTouchEnd);
		var self = plus.webview.currentWebview();
		sourceData = self.sourceData
		nurseid = sourceData['nurseid']
		if (sourceData['rw'] && sourceData['rw'] != '') {
			$('.mui-content')[0].classList.add('hasrw')
		}
		perList = sourceData['locSchArr']
		mui('#dataArea')[0].innerHTML = sourceData.startDate+' 至 '+sourceData.endDate+'人员排序'
		topHeight = 44 + $('#dataArea')[0].clientHeight;
		updatePersonList();
	}
	
	function upDownBtnTapped(iconDon,type){
		if (notSchedTip()) return
		var tr = iconDon.parentNode.parentNode
		var id = tr.getAttribute('data-id')
		var sort = tr.getAttribute('data-sort')
		var trClass = tr.getAttribute('class');
		if (trClass.indexOf('person') != -1) { //移动人员
			var otherDom = ''
			if (type == 'U') { //上
				otherDom = tr.previousElementSibling
				if (!otherDom || sort=='1') {
					mui.toast('已经是第一喽')
					return
				}
			}else{
				otherDom = tr.nextElementSibling
				if (!otherDom || (otherDom.getAttribute('class').indexOf('person') != -1&& otherDom.getAttribute('data-row') == "")) {
					mui.toast('已经是最后一个喽')
					return
				}
			}
			
			var otherClass = otherDom.getAttribute('class')
			var parr=""
			if (otherClass.indexOf('person') != -1) { //other是人
				var otherSort=otherDom.getAttribute('data-sort')
				parr = otherDom.getAttribute('data-row')+'「'+ sort+'@'+ tr.getAttribute('data-row')+'「'+otherSort+'「'+tr.getAttribute('data-group')
				otherDom.setAttribute ('data-sort',sort)
				tr.setAttribute ('data-sort',otherSort)
			}else { //是分组
				if (type == 'U') {
					if (!otherDom.previousElementSibling) {
						mui.toast('已经是最后一个喽')
						return
					}else{
						parr = tr.getAttribute('data-row')+'「'+sort+'「'+otherDom.previousElementSibling.getAttribute('data-group')
					}
				}else{
					parr = tr.getAttribute('data-row')+'「'+sort+'「'+otherDom.getAttribute('data-group')
				}
			}
			changeArgShort(parr,function(isFail){ //保存结果
				if (isFail) {
					return
				}
				if (type == 'U') {
					$('#tbody')[0].removeChild(tr);
					$('#tbody')[0].insertBefore(tr,otherDom)
				}else{
					$('#tbody')[0].removeChild(otherDom);
					$('#tbody')[0].insertBefore(otherDom,tr)
				}
			})
		}else{ //上移分组
			var parr = sourceData['rw'] +'^'+tr.getAttribute('data-group') //排班表id^移动组Id
			changeArgGroup(parr,type,getWardPersonList)
		}
	}
	
	function dragBarsIconTapped(){
		var tr = this.parentNode.parentNode
		var oldActive = $('.person.active')[0]
		if (oldActive && tr != oldActive) {
			oldActive.classList.remove('active')
			$('tr.select')[0].classList.remove('select')
		}
		var abs = getElementAbsPosition(tr)
		$('#copyDom')[0].querySelector('.dom').innerHTML = tr.innerText
		$('#copyDom')[0].style.display = 'flex'
		var top = abs.top +$('#wrapper').scroll().y
		if (top < topHeight) {
			top = topHeight
		}else if (top > screen.height - bottomHeight) {
			top = screen.height - bottomHeight
		}
		$('#copyDom')[0].style.top = top + 'px'
		tr.classList.add('active')
		var preTr = tr.previousElementSibling
		if (preTr) {
			preTr.classList.add('select')
		}
	}
	
	function copyDomTouchStart(e){
		var y = e.targetTouches[0].clientY - copyDomHeight/2
		if (y < topHeight ) {
			y = topHeight
		}else if (y > screen.height - bottomHeight) {
			y = screen.height - bottomHeight
		}
		$('#copyDom')[0].style.top = y +'px'
		lastY = y
	}
	
	function copyDomTouchMove(e){
		var y = e.targetTouches[0].clientY - copyDomHeight/2
		if (y < topHeight ) {
			y = topHeight
		}else if (y > screen.height -bottomHeight) {
			y = screen.height - bottomHeight
		}
		if (moveTimer && lastY != y) {
			clearInterval(moveTimer)
			moveTimer = undefined
		}
		lastY = y
		$('#copyDom')[0].style.top = y +'px'
		var scrollY = $('#wrapper').scroll().y
		var trs = document.querySelectorAll('tr')
		for (var i = 0; i < trs.length;i++) {
			var tr = trs[i]
			var trHeight = tr.clientHeight
			if (trHeight < 2) {
				continue
			}
			var top = getElementAbsPosition(tr).top + scrollY
			if (y < top ) {
				continue
			}
			if (y > top + trHeight) {
				continue
			}
			if (tr.getAttribute('class').indexOf('person') != -1 && tr.getAttribute('data-row') == "") {
				break
			}
			var oldActive = $('tr.select')[0]
			if (oldActive) {
				oldActive.classList.remove('select')
			}
			tr.classList.add('select')
		}
		if (scrollY > -20 || overHeight <= 0 || Math.abs(scrollY) >= overHeight) {
			if (moveTimer) {
				clearInterval(moveTimer)
				moveTimer = undefined
			}
			return
		}
		if (moveTimer) {
			return
		}
		var offset = 20
		if (y < topHeight + 20) {
			offset = 20
		}else if (y > screen.height - bottomHeight - 20) {
			offset = -20
		}else{
			if (moveTimer) {
				clearInterval(moveTimer)
				moveTimer = undefined
			}
			return
		}
		
		moveTimer = setInterval(function() {
			var currScrollY = $('#wrapper').scroll().y
			if (currScrollY > -20 || Math.abs(currScrollY) >= overHeight) {
				clearInterval(moveTimer)
				moveTimer = undefined;
			}
			mui('#wrapper').scroll().scrollTo(0,currScrollY + offset,100);
		}, 200);
	}
	function copyDomTouchEnd(){
		if (moveTimer) {
			clearInterval(moveTimer)
			moveTimer = undefined
		}
		if (notSchedTip()) {
			$('tr.active')[0].classList.remove('active')
			if ($('tr.select')[0]) {
				$('tr.select')[0].classList.remove('select')
			}
			$('#copyDom')[0].style.display = 'none'
			return
		}
		var tr = $('tr.select')[0]
		var activeTr = $('.person.active')[0]
		if (!tr) {
			activeTr.classList.remove('active')
			return
		}
		if (activeTr.previousElementSibling == tr) {
			activeTr.classList.remove('active')
			tr.classList.remove('select')
			return
		}
		dragArgSort(activeTr.getAttribute('data-id'),tr.getAttribute('data-id'));
	}
	
	function dragArgSort(activeId,selectId){
		var selectTr = $('tr[data-id="'+selectId+'"]')[0]
		var activeTr =  $('tr[data-id="'+activeId+'"]')[0]
		var selectSort = parseInt(selectTr.getAttribute('data-sort'))
		var activeSort = parseInt(activeTr.getAttribute('data-sort'))
		var selectTrNext = selectTr.nextElementSibling
		var parr = ''
		if (!selectTrNext) {
			parr = dragDown(activeTr,selectTr,activeId,selectId,selectTrNext)
		}else if (isNaN(selectSort)){ //selectTr是分组
			var sort = parseInt(selectTrNext.getAttribute('data-sort'))
			if ( activeSort > sort) {//向上
				parr = dragUp(activeTr,selectTr,activeId,selectId,sort)
			}else{
				parr = dragDown(activeTr,selectTr,activeId,selectId,selectTrNext)
			}
		}else if (activeSort > selectSort) { //向上
			parr = dragUp(activeTr,selectTr,activeId,selectId,selectSort+1)
		}else{ //向下
			parr = dragDown(activeTr,selectTr,activeId,selectId,selectTrNext)
		}
		if (parr == '' || !parr) {
			updatePersonList()
			$('#copyDom')[0].style.display = 'none'
			return
		}
		changeArgShort(parr,function(isFail){ //保存结果
			if (isFail) {
				return
			}
			var tbody = $('#tbody')[0]
			tbody.removeChild(activeTr);
			if (!selectTrNext) {
				tbody.appendChild(activeTr)
			}else{
				tbody.insertBefore(activeTr,selectTrNext)
			}
			activeTr.classList.remove('active')
			selectTr.classList.remove('select')
			$('#copyDom')[0].style.display = 'none'
		})
	}
	
	function dragUp(activeTr,selectTr,activeId,selectId,destSort){
		var parr = ''
		var next
		for (var i =0; i < perList.length;i++) {
			if (!next) {
				next = selectTr.nextElementSibling
			}else{
				next = next.nextElementSibling
			}
			
			if (!next) {
				break
			}
			if (next.getAttribute('class').indexOf('person') == -1) { //是分组
				continue;
			}
			var rowId = next.getAttribute('data-row')
			//3028「8@3029「9@3030「10@3031「11@3032「7「-
			if (next == activeTr) {
				activeTr.setAttribute('data-sort',destSort)
				if (parr!= '') {
					parr += '@'
				}
				parr += activeTr.getAttribute('data-row')+'「'+destSort+'「'+selectTr.getAttribute('data-group');
				break
			}
			var tempSort = parseInt(next.getAttribute('data-sort'))
			next.setAttribute('data-sort',tempSort+1)
			if (parr != '') {
				parr += '@'
			}
			parr += rowId+'「'+(tempSort+1); 
		}
		return parr
	}
	
	function dragDown(activeTr,selectTr,activeId,selectId,selectTrNext){
		var parr = ''
		var lastSort,lastGroup
		var next
		for (var i =0; i < perList.length;i++) {
			if (!next) {
				next = activeTr.nextElementSibling
			}else{
				next = next.nextElementSibling
			}
			if (!next) {
				if (!selectTrNext) { //拖拽到最后一行
					activeTr.setAttribute('data-sort',lastSort)
					parr += '@' + activeTr.getAttribute('data-row')+'「'+lastSort+'「'+lastGroup;
				}
				break
			}
			var isPerson = next.getAttribute('class').indexOf('person')!= -1
			
			var rowId = next.getAttribute('data-row')
			var tempSort = parseInt(next.getAttribute('data-sort'))
			if (next == selectTr) {
				if (parr == '') { //只交换一个位置
					if (!isPerson) { //是和分组交换位置
						parr = '';
						lastSort = activeTr.getAttribute('data-sort')
					}else{
						parr = rowId+'「'+(tempSort-1);
					}
				}
				if (!isPerson) { //selectTr的是分组
					activeTr.setAttribute('data-sort',lastSort)
					if (parr != '') {
						parr += '@' 
					}
					parr += activeTr.getAttribute('data-row')+'「'+lastSort+'「'+next.getAttribute('data-group');
				} else {
					if (!selectTrNext) { //拖动到最后面
						next.setAttribute('data-sort',tempSort-1)
						parr += '@' + next.getAttribute('data-row')+'「'+(tempSort-1)+'「'+next.getAttribute('data-group');
					}
					activeTr.setAttribute('data-sort',tempSort)
					parr += '@' + activeTr.getAttribute('data-row')+'「'+tempSort+'「'+next.getAttribute('data-group');
				}
				break
			}
			if (!isPerson) {
				continue
			}
			lastSort = tempSort
			lastGroup = next.getAttribute('data-group')
			next.setAttribute('data-sort',tempSort-1)
			if (parr != '') {
				parr += '@'
			}
			parr += rowId+'「'+(tempSort-1); //3028「8@3029「9@3030「10@3031「11@3032「7「-
		}
		return parr
	}
	
	function notSchedTip(){
		if (sourceData['isOverdue']) {
			mui.toast('已超出修改期限')
			return 1
		}
		
		if (sourceData['rw'] == "") {
			mui.confirm('暂未形成排班无法操作,形成排班吗?','温馨提示',['取消','排班'],function (e) {
				if (e.index == 1) {
					var schLocPage = plus.webview.getWebviewById('nurSchLoc')
					if (schLocPage) {
						schLocPage.evalJS('refreshPageData("create","nurSchPerSet","updateScourceData")')
					}
				}
			})
			return 1
		}
		return 0
	}
	
	function showNullTip(msg,type){
		mui('#nullData')[0].style.display = 'block';
		mui('#nullTip')[0].innerHTML = msg
	}
	function hideNullTip(){
		mui('#nullData')[0].style.display = 'none';;
	}
	function updateScourceData(argInfo,locSchArr,tempIndex){
		sourceData['locSchArr'] = locSchArr
		sourceData['argInfo'] = argInfo
		sourceData['rw'] = argInfo['rw']
		$('.mui-content')[0].classList.add('hasrw')
		perList = locSchArr
	}
	var exportObj = {}
	exportObj.updateScourceData = function(argInfo,locSchArr,tempIndex){
		updateScourceData(argInfo,locSchArr,tempIndex)
	};
	return exportObj
})(mui)
function updateScourceData(argInfo,locSchArr,tempIndex){
	schPerSet.updateScourceData(argInfo,locSchArr,tempIndex)
}
